/*
 *所有关于SalesOut类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*SalesOutService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using VOL.Core.BaseProvider;
using VOL.Core.Extensions.AutofacManager;
using VOL.Entity.DomainModels;
using System.Linq;
using VOL.Core.Utilities;
using System.Linq.Expressions;
using VOL.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Domain.IRepositories;
using VOL.Domain.Dto;
using System;
using System.Threading.Tasks;
using VOL.Domain.Infrastructure;

namespace VOL.Domain.Services
{
    public partial class SalesOutService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ISalesOutRepository _repository;//访问数据库
        private readonly IBaseRepository<SalesOut> _salesOutbaseRepository;
        private readonly IBaseRepository<Customer> _customerRepository;
        [ActivatorUtilitiesConstructor]
        public SalesOutService(
            ISalesOutRepository dbRepository,
            IHttpContextAccessor httpContextAccessor,
            IBaseRepository<SalesOut> salesOutbaseRepository,
            IBaseRepository<Customer> customerRepository    
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            _salesOutbaseRepository = salesOutbaseRepository;
            _customerRepository = customerRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }

        /// <summary>
        /// 获取销售出库分页数据
        /// </summary>
        /// <param name="dto">查询条件</param>
        /// <returns>分页数据</returns>
        public async Task<PageGridData<SalesOut>> GetSalesOutPages(GetSalesOutDto dto)
        {
            var query = _salesOutbaseRepository.GetAll(x => true);
            query = query.WhereIF(!string.IsNullOrWhiteSpace(dto.OutCode), x => x.OutCode.Contains(dto.OutCode))
                         .WhereIF(!string.IsNullOrWhiteSpace(dto.SalesCode), x => x.SalesCode.Contains(dto.SalesCode))
                         .WhereIF(!string.IsNullOrWhiteSpace(dto.CustomerName), x => x.CustomerName.Contains(dto.CustomerName))
                         .WhereIF(!string.IsNullOrWhiteSpace(dto.OutDate), x => x.OutTime.HasValue && x.OutTime.Value.Date == DateTime.Parse(dto.OutDate).Date)
                         .WhereIF(dto.Status.HasValue, x => x.Status == dto.Status.Value)
                         .OrderByDescending(x => x.OutTime);

            var total = await query.CountAsync();
            var items = await query.Skip((dto.PageIndex - 1) * dto.PageSize)
                                  .Take(dto.PageSize)
                                  .ToListAsync();

            return new PageGridData<SalesOut>
            {
                total = total,
                rows = items
            };
        }

        public async Task<bool> AddSalesOutAsync(SalesOut entity)
        {
            if (entity == null)
                return false;
            await _salesOutbaseRepository.Add(entity);
            return true;
        }

        public async Task<bool> UpdateSalesOutAsync(SalesOut entity)
        {
            if (entity == null || entity.Id <= 0)
                return false;
            var dbEntity =  _salesOutbaseRepository.GetAll().FirstOrDefault(x => x.Id == entity.Id);
            if (dbEntity == null)
                return false;
            dbEntity.OutCode = entity.OutCode;
            dbEntity.SalesCode = entity.SalesCode;
            dbEntity.CustomerName = entity.CustomerName;
            dbEntity.OutTime = entity.OutTime;
            dbEntity.Status = entity.Status;
            await _salesOutbaseRepository.Update(dbEntity);
            return true;
        }

        public async Task<bool> UpdateSalesOutStatusAsync(int id, int status)
        {
            var dbEntity = _salesOutbaseRepository.GetAll().FirstOrDefault(x => x.Id == id);
            if (dbEntity == null)
                return false;
            dbEntity.Status = status;
            if(status == 3)
            {
                dbEntity.OutTime = DateTime.Now;
            }
          
            await _salesOutbaseRepository.Update(dbEntity);
            return true;
        }

        /// <summary>
        /// 批量删除销售出库单
        /// </summary>
        /// <param name="ids">待删除的记录ID数组</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> BatchDeleteSalesOut(int[] ids)
        {
            var result = new WebResponseContent();
            if (ids == null || ids.Length == 0)
            {
                return result.Error("未选择要删除的记录");
            }

            try
            {
                // 查询要删除的记录
                var entities = await _salesOutbaseRepository.FindAsync(x => ids.Contains(x.Id));
                if (entities.Count == 0)
                {
                    return result.Error("未找到要删除的记录");
                }

                // 执行批量删除
                int rows = await _salesOutbaseRepository.DeleteAsync(x => ids.Contains(x.Id));

                if (rows > 0)
                {
                    return result.OK($"成功删除{rows}条记录");
                }
                else
                {
                    return result.Error("删除失败");
                }
            }
            catch (Exception ex)
            {
                return result.Error($"删除异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 查询客户信息
        /// </summary>
        /// <param name="dto">查询条件</param>
        /// <returns>客户列表</returns>
        public async Task<PageGridData<Customer>> GetCustomerList(GetCustomerDto dto)
        {
            // 构建查询
            var query = _customerRepository.GetAll();
            
            // 应用筛选条件
            query = query.WhereIF(!string.IsNullOrWhiteSpace(dto.CustCode), x => x.CustCode.Contains(dto.CustCode))
                        .WhereIF(!string.IsNullOrWhiteSpace(dto.CustName), x => x.CustName.Contains(dto.CustName))
                        .WhereIF(!string.IsNullOrWhiteSpace(dto.CustAbbreviation), x => x.CustAbbreviation.Contains(dto.CustAbbreviation))
                        .WhereIF(!string.IsNullOrWhiteSpace(dto.CustType), x => x.CustType.Contains(dto.CustType))
                        .WhereIF(dto.IsEnable.HasValue, x => x.IsEnable == dto.IsEnable.Value)
                        .OrderByDescending(x => x.CustId);
            
            // 获取总数
            var total = await query.CountAsync();
            
            // 获取分页数据
            int pageIndex = dto.PageIndex <= 0 ? 1 : dto.PageIndex;
            int pageSize = dto.PageSize <= 0 ? 20 : dto.PageSize;
            var items = await query.Skip((pageIndex - 1) * pageSize)
                                .Take(pageSize)
                                .ToListAsync();
            
            // 返回分页数据
            return new PageGridData<Customer>
            {
                total = total,
                rows = items
            };
        }
    }
}
